package com.onesports.intelligent.k12.polarlight.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.onesports.framework.kit.common.util.ParamUtils;
import com.onesports.intelligent.k12.polarlight.common.errors.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * 高德地图工具类
 *
 * @author clw
 * @date 2022-07-14 16:45:04
 */
//@Component
@Slf4j
public class GouldUtil {

    private static final String GOULD_KEY= "bf9a8326ef455c2572ebce27fd70bdcc";

    public static void main(String[] args) throws JsonProcessingException {
        Long a = getDistance("118.089425,24.479833","117.969218,24.459849");
        System.out.println("距离："+a+"米");
    }

    /**
     * 发送请求
     * @param serverUrl 请求地址
     */
    private static String getResponse(String serverUrl) {
        // 用JAVA发起http请求，并返回json格式的结果
        StringBuffer result = new StringBuffer();
        try {
            URL url = new URL(serverUrl);
            URLConnection conn = url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            in.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 2.根据两个定位点的经纬度算出两点间的距离
     * @param startLonLat 起始经纬度
     * @param endLonLat 结束经纬度（目标经纬度）
     * @return 两个定位点之间的距离
     */
    public static long getDistance(String startLonLat, String endLonLat) throws JsonProcessingException {
        // 返回起始地startAddr与目的地endAddr之间的距离，单位：米
        Long result = 0L;
        String queryUrl = "http://restapi.amap.com/v3/distance?key="+GOULD_KEY+"&origins=" + startLonLat + "&destination="
            + endLonLat;
        String queryResult = getResponse(queryUrl);
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(queryResult);
        JsonNode elements = jsonNode.get("results");
        if(ParamUtils.isEmpty(elements)){
            throw new BusinessException("查无数据!");
        }
        //从0开始
        JsonNode object2 = elements.get(0);
        JsonNode distance = object2.get("distance");
        result = distance.asLong();
        return result;
    }
}
